package com.example.security.config;

import com.example.security.bean.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class Subject {


    private ThreadLocal<Authentication> threadLocal=new ThreadLocal<Authentication>();



    /**
     * 登录认证
     * @param token
     */
    public void login(CustomizedToken token){
        SecurityContextHolder.getContext().setAuthentication(token);
        threadLocal.set(SecurityContextHolder.getContext().getAuthentication());
    }


    public LoginUser getLoginUser(){
        Authentication authentication= getAuthentication();
        if(authentication!=null){
            LoginUser loginUser=(LoginUser)   authentication.getPrincipal();
            return loginUser;
        }
        return null;
    }





    private Authentication getAuthentication(){
        Authentication authentication= threadLocal.get();
       if(authentication!=null){
           authentication=SecurityContextHolder.getContext().getAuthentication();
           threadLocal.set(authentication);
       }
       return threadLocal.get();
    }



    public static void main(String[] args) {

        Subject subject=new Subject();
        CustomizedToken customizedToken=new CustomizedToken("","","","");
        subject.login(customizedToken);
        subject.getLoginUser();





    }







}
